﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Security;

namespace FAfx.BootstrapWizard
{
    [UserIsValid(ErrorMessage = "Sorry, we cannot login with this username/password combination")]
    public class LoginModel
    {
        [Display(Name="User Name")]
        [Required()]
        public string UserName { get; set; }
        [Required()]
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }

    [AttributeUsage(AttributeTargets.Class)]
    internal class UserIsValidAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (validationContext == null)
                return null;

            var userName = validationContext.ObjectType.GetProperty("UserName");
            var password = validationContext.ObjectType.GetProperty("Password");

            if (userName == null || password == null)
                throw new NotSupportedException("Missing UserName or Password on the LoginModel class");

            if (!userName.IsDefined(typeof(RequiredAttribute), false) || !password.IsDefined(typeof(RequiredAttribute), false))
                throw new NotSupportedException("UserName or Password is missing the Required attribute on the LoginModel class");

            var userNameValue = (string)userName.GetValue(validationContext.ObjectInstance, null);
            var passwordValue = (string)password.GetValue(validationContext.ObjectInstance, null);

            if (String.IsNullOrWhiteSpace(userNameValue) || String.IsNullOrWhiteSpace(passwordValue))
                return null;// lets only validate login when username/password validate

            if (Membership.ValidateUser(userNameValue, passwordValue))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);
            }
        }
    }


    public partial class login : System.Web.UI.Page
    {
        public void fvLogin_InsertItem()
        {
            var item = new FAfx.BootstrapWizard.LoginModel();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                Login(item);
            }
        }

        private void Login(LoginModel login)
        {
            if (login.RememberMe)
            {
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(login.UserName, true, 12 * 60);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                cookie.Expires = authTicket.Expiration;
                HttpContext.Current.Response.Cookies.Set(cookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(login.UserName, false);
            }
            Response.Redirect(Request.Url.AbsoluteUri, true);
        }
    }
}